package com.zjt.smart.api.intercepter;

import java.io.IOException;
import java.util.Map;

import okhttp3.HttpUrl;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;

/**
 * @author zhengjianting
 * @time 2017/8/25 0025 上午 11:31
 */

public class HeaderInterceptor implements Interceptor {
    private Map<String, Object> header;

    @Override
    public Response intercept(Chain chain) throws IOException {
//        Request oldRequest = chain.request();
//        Request request = addParam(oldRequest);
        Request request = chain.request();
        Request.Builder builder = request
                .newBuilder()
                .header("Accept", "application/json")
                .header("Content-Type", "application/json");

        setRequestBuilderHeader(builder);
//        addHttpClientRASHead(builder);

        return chain.proceed(builder.build());
    }

    private void setRequestBuilderHeader(Request.Builder builder) {
        if (header == null) return;
        for (Map.Entry<String, Object> entry : header.entrySet()) {
            builder.header(entry.getKey(), (String)entry.getValue());
        }
    }

    public void setHeader(Map<String, Object> header) {
        this.header = header;
    }

    /*
    * 添加公共请求header
    *
    * */
    private static void addHttpClientRASHead(Request.Builder builder) {
        builder.addHeader("a", "a");
        builder.addHeader("b", "b");
        builder.addHeader("c", "c");
    }

    /**
     * 添加公共参数
     * @param oldRequest
     * @return
     */
    private Request addParam(Request oldRequest) {
        HttpUrl.Builder builder = oldRequest.url()
                .newBuilder()
                .setEncodedQueryParameter("a", "a")
                .setEncodedQueryParameter("b", "b")
                .setEncodedQueryParameter("c", "c");

        Request newRequest = oldRequest.newBuilder()
                .method(oldRequest.method(), oldRequest.body())
                .url(builder.build())
                .build();
        return newRequest;
    }

}
